package com.sr.maven.servlet.base;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class ModelBaseServlet extends ViewBaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.在所有的request.getParameter（）前面设置解析请求体的字符集
        req.setCharacterEncoding("UTF-8");

        //2.从请求参数中获取method对应的数据
        String method = req.getParameter("method");

        //3。通过反射调用method对应的方法
        //这里使用this. 是获取的子类的类型，因为真正执行的时候 是走的子类
        Class<? extends ModelBaseServlet> clazz = this.getClass();

        try{
            //获取method对应的Method对象
            Method methodObject = clazz.getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);

            //打开访问权限
            methodObject.setAccessible(true);

            //通过method调用方法
            methodObject.invoke(this,req,resp);

        }catch (Exception e){
            e.printStackTrace();
            //无论什么项目，都要把异常包装成 运行时异常抛出
            throw  new RuntimeException(e);
        }
    }
}
